package com.xiaoyg.threadlocal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadLocalTest {

    //第一种初始化方式
    /**
     * 声明为static是让ThreadLocal实例随着程序的结束才结束，这样才不会让GC回收了
     * 声明为final是让ThreadLocal实例引用不会被替换，这样子也不会因为被替换导致被GC回收
     * 这两个声明都是为了避免作为key的ThreadLocal对象没有外部强引用而导致被GC回收，从而导致内存泄漏的问题，因为ThreadLocalMap<ThreadLocal, Object>中的ThreadLocal
     * 对象作为key是弱引用，会被GC回收。
     *
     *
     */
    private static final ThreadLocal<String> threadLocalStr = ThreadLocal.withInitial(() -> "fresh");
    private static AtomicInteger intGen = new AtomicInteger(0);


    //第二种初始化方式
    private static final ThreadLocal<Integer> threadLocalInt = ThreadLocal.withInitial(() -> intGen.incrementAndGet());




    public static void main(String[] args) throws InterruptedException {
        List<Thread> threads = new ArrayList<>();

        for (int i = 0; i < 2; i++) {
            Thread t = new Thread(()->{
                try {
                    System.out.println(Thread.currentThread().getName() + "   " + threadLocalInt.get());
                    System.out.println(Thread.currentThread().getName() + "   " + threadLocalStr.get());
                    TimeUnit.SECONDS.sleep(5);
                    threadLocalStr.set("bojack horseman" + threadLocalInt.get());
                    System.out.println(Thread.currentThread().getName() + "   " + threadLocalInt.get());
                    System.out.println(Thread.currentThread().getName() + "   " + threadLocalStr.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    threadLocalInt.remove();
                    threadLocalStr.remove();
                }
            });
            t.start();
            threads.add(t);
        }
        TimeUnit.SECONDS.sleep(2);
        System.out.println(threads);
        System.out.println(threadLocalStr);
        System.out.println(threadLocalInt);
    }




}
